import { defineComponent, computed } from 'vue'
import { getFixedTotalWidthByColumnKey } from '../util'
import { use样式 } from 'amtf/hooks'
import {
  getValByUnit,
  拼组件名,
  isFunction,
  isBoolean,
  getRandomId,
} from 'amtf/utils'
const 主名 = 'table-body-td'
const 组件名 = 拼组件名(主名)

export default defineComponent({
  name: 组件名,
  props: {
    rowData: {
      type: Object,
      required: true,
    },
    column: {
      type: Object,
      required: true,
    },
    rowIndex: {
      type: Number,
      required: true,
    },
    colgroups: {
      type: Array,
      required: true,
    },
    rowKeyFieldName: {
      type: String,
      default: null,
    },
    // cell span option
    cellSpanOption: {
      type: Object,
      default: () => null,
    },
    // cell style option
    cellStyleOption: {
      type: Object,
      default: () => null,
    },
    // event custom option
    eventCustomOption: {
      type: Object,
      default: () => null,
    },
    // cell selection key data
    cellSelectionData: {
      type: Object,
      default: () => null,
    },
    // footer rows
    footerRows: {
      type: Array,
      default: () => [],
    },
    // fixed footer
    fixedFooter: {
      type: Boolean,
      default: true,
    },
  },
  setup(props) {
    const { 拼样式名_table直属 } = use样式(主名)
    const isLastLeftFixedColumn = computed(() => {
      let result = false
      const { colgroups, column } = props
      const { fixed } = column
      if (fixed === 'left') {
        const { field } = column
        const leftFixedColumns = colgroups.filter((x) => x.fixed === 'left')
        const index = leftFixedColumns.findIndex((x) => x.field === field)
        if (index === leftFixedColumns.length - 1) {
          result = true
        }
      }
      return result
    })

    const isfirstRightFixedColumn = computed(() => {
      let result = false
      const { colgroups, column } = props
      const { fixed } = column
      if (fixed === 'right') {
        const { field } = column
        const leftFixedColumns = colgroups.filter((x) => x.fixed === 'right')
        if (leftFixedColumns[0].field === field) {
          result = true
        }
      }
      return result
    })

    const getBodyTdClass = ({ fixed }) => {
      let result = {
        [拼样式名_table直属('footer-td')]: true,
      }
      const {
        cellStyleOption,
        rowData,
        column,
        rowIndex,
        cellSelectionData,
        rowKeyFieldName,
      } = props
      // column fixed
      if (fixed) {
        result[拼样式名_table直属('fixed-left')] = fixed === 'left'
        result[拼样式名_table直属('fixed-right')] = fixed === 'right'
        result[拼样式名_table直属('last-left-fixed-column')] =
          isLastLeftFixedColumn.value
        result[拼样式名_table直属('first-right-fixed-column')] =
          isfirstRightFixedColumn.value
      }
      // cell style option
      if (
        cellStyleOption &&
        typeof cellStyleOption.footerCellClass === 'function'
      ) {
        const customClass = cellStyleOption.footerCellClass({
          row: rowData,
          column,
          rowIndex,
        })
        if (customClass) {
          result[customClass] = true
        }
      }
      // cell selection option
      if (cellSelectionData) {
        const { rowKey, colKey } = cellSelectionData.currentCell
        if (rowData[rowKeyFieldName] === rowKey && column['key'] === colKey) {
          result[拼样式名_table直属('cell-selection')] = true
        }
      }
      return result
    }

    const getBodyTdStyle = ({ key, align, fixed }) => {
      let result = {}
      const { colgroups, rowIndex, footerRows } = props
      // text align
      result['text-align'] = align || 'center'
      // fixed left total width or right total width
      if (fixed) {
        let totalWidth = 0
        // column index
        const columnIndex = colgroups.findIndex((x) => x.key === key)
        if (
          (fixed === 'left' && columnIndex > 0) ||
          (fixed === 'right' && columnIndex < colgroups.length - 1)
        ) {
          totalWidth = getFixedTotalWidthByColumnKey({
            colgroups,
            colKey: key,
            fixed,
          })
          totalWidth = getValByUnit(totalWidth)
        }
        result['left'] = fixed === 'left' ? totalWidth : ''
        result['right'] = fixed === 'right' ? totalWidth : ''
      }
      // footer rows th fixed bottom
      if (props.fixedFooter) {
        let rowHeight = 0
        // console.log(`rowIndex 👉`, rowIndex)
        // console.log(`footerRows 👉`, footerRows)
        // console.log(`props.footerRows 👉`, props.footerRows)

        // console.log(`rowIndex 👉`, rowIndex)
        // console.log(`footerRows.length 👉`, footerRows.length)
        if (rowIndex !== footerRows.length - 1) {
          // console.log(`rowIndex 👉`, rowIndex)
          rowHeight = footerRows.reduce((total, currentVal, index) => {
            // console.log(`currentVal 👉`, currentVal)
            return index > rowIndex ? currentVal.rowHeight + total : total
          }, 0)
        }
        // console.log(`rowHeight 👉`, rowHeight)
        rowHeight = getValByUnit(rowHeight)
        result['bottom'] = rowHeight
      }
      return result
    }

    const getRenderContent = () => {
      let content = null
      const { column, rowData, rowIndex } = props
      // has render function
      if (typeof column.renderFooterCell === 'function') {
        const renderResult = column.renderFooterCell({
          row: rowData,
          column,
          rowIndex,
        })
        content = renderResult
      } else {
        content = rowData[column.field]
      }
      return content
    }

    const getCellSpan = () => {
      const { cellSpanOption, rowData, column, rowIndex } = props
      let rowspan = 1
      let colspan = 1
      if (cellSpanOption) {
        const { footerCellSpan } = cellSpanOption
        if (typeof footerCellSpan === 'function') {
          const result = footerCellSpan({
            row: rowData,
            column,
            rowIndex,
          })
          if (typeof result === 'object') {
            rowspan = result.rowspan
            colspan = result.colspan
          }
        }
      }
      return { rowspan, colspan }
    }

    const cellClick = (e, fn) => {
      fn && fn(e)
    }

    const cellDblclick = (e, fn) => {
      fn && fn(e)
    }

    const cellContextmenu = (e, fn) => {
      fn && fn(e)
    }

    const cellMouseenter = (e, fn) => {
      fn && fn(e)
    }

    const cellMouseleave = (e, fn) => {
      fn && fn(e)
    }

    const cellMousemove = (e, fn) => {
      fn && fn(e)
    }

    const cellMouseover = (e, fn) => {
      fn && fn(e)
    }

    const cellMousedown = (e, fn) => {
      fn && fn(e)
    }

    const cellMouseup = (e, fn) => {
      fn && fn(e)
    }

    // custom on cell event
    let customEvents = {}
    if (props.eventCustomOption) {
      const { footerCellEvents } = props.eventCustomOption
      customEvents = footerCellEvents
        ? footerCellEvents({
            row: props.rowData,
            column: props.column,
            rowIndex: props.rowIndex,
          })
        : {}
    }

    const events = {
      onClick: (e) => cellClick(e, customEvents.click),
      onDblclick: (e) => cellDblclick(e, customEvents.dblclick),
      onContextmenu: (e) => cellContextmenu(e, customEvents.contextmenu),
      onMouseenter: (e) => cellMouseenter(e, customEvents.mouseenter),
      onMouseleave: (e) => cellMouseleave(e, customEvents.mouseleave),
      onMousemove: (e) => cellMousemove(e, customEvents.mousemove),
      onMouseover: (e) => cellMouseover(e, customEvents.mouseover),
      onMousedown: (e) => cellMousedown(e, customEvents.mousedown),
      onMouseup: (e) => cellMouseup(e, customEvents.mouseup),
    }

    return () => {
      const { rowspan, colspan } = getCellSpan()
      if (!rowspan || !colspan) {
        return null
      }

      return (
        <td
          class={getBodyTdClass(props.column)}
          style={getBodyTdStyle(props.column)}
          rowspan={rowspan}
          colspan={colspan}
          onClick={events.click}
          onDblclick={events.dblclick}
          onContextmenu={events.contextmenu}
          onMouseenter={events.mouseenter}
          onMouseleave={events.mouseleave}
          onMousemove={events.mousemove}
          onMouseover={events.mouseover}
          onMousedown={events.mousedown}
          onMouseup={events.mouseup}
        >
          {getRenderContent()}
        </td>
      )
    }
  },
})
